
function BannerShow(obj){
    this.el = this.getEl(obj.el),
    this.pics = this.gets('.pic',this.el),
    this.seconds = obj.seconds || 1000
    this.autoplay = obj.autoplay || false
    this.curI = obj.curI || 0,
    this.pics[this.curI].classList.add('opacity')
    this.all()
}
// 获取单个元素
BannerShow.prototype.$ = function (el,parent){
    parent = parent || document;
    return parent.querySelector(el);
}
// 获取元素数组
BannerShow.prototype.gets = function (el,parent){
    parent = parent || document;
    return [...parent.querySelectorAll(el)]
}
// 判断el类型
BannerShow.prototype.getEl = function(el){
    if(el.nodeType === 1){
        return el
    }else if(typeof(el) === 'string'){
        return this.$(el)
    }else{
        throw new Error('el参数错误')
    }
}
BannerShow.prototype.all = function (){
    this.$('.page',this.el) && this.pages()
    this.$('.next',this.el) && this.butFn()
    this.autoplay && this.autoplayFn()
}

// 渲染分页器并设置点击事件
BannerShow.prototype.pages = function (){
     this.$('.page',this.el).innerHTML = this.pics.map((pic)=>{
        return `<span></span>`
     }).join('')
    this.tab = this.gets('span', this.$('.page',this.el))
    this.tab[this.curI].classList.add('active')
    this.clickFn()
}
// 设置点击事件
BannerShow.prototype.clickFn = function(){
    this.tab.forEach((span,i)=>{
        span.addEventListener('click',()=>{
            this.activeFn(i)
        })  
    })
}
// 设置上下事件
BannerShow.prototype.butFn = function(){
    this.$('.next',this.el).addEventListener('click',this.nextFn.bind(this))
    this.$('.pver',this.el).addEventListener('click',this.pverFn.bind(this))
}
// 下一张函数
BannerShow.prototype.nextFn = function(){
    let i = this.curI + 1
        if(i > this.pics.length-1) i = 0
        this.activeFn(i)
}
// 上一张函数
BannerShow.prototype.pverFn = function(){
    let i = this.curI - 1
    if(i < 0 ) i = this.pics.length-1
    this.activeFn(i)
}
// 自动轮播
BannerShow.prototype.autoplayFn = function(){
    this.timer = setInterval(this.nextFn.bind(this),this.seconds)
    this.el.addEventListener('mouseover',()=>{
        clearInterval(this.timer)
    })
    this.el.addEventListener('mouseout',()=>{
        this.timer = setInterval(this.nextFn.bind(this),this.seconds)
    })
} 
// 封装切换函数
BannerShow.prototype.activeFn = function(i){
    this.tab && this.tab[this.curI].classList.remove('active')
    this.pics[this.curI].classList.remove('opacity')
    this.curI = i
    this.tab && this.tab[this.curI].classList.add('active')
    this.pics[this.curI].classList.add('opacity')
}
let banner1 = new BannerShow({
    el : '.banner1',
    seconds : 2000,
    autoplay : true
})
let banner2 = new BannerShow({
    el : document.querySelector('.banner2'),
}),
    banner3 = new BannerShow({
        el : '.banner3',
        autoplay : true
    }),
    banner4 = new BannerShow({
        el : '.banner4',
        autoplay : true
    })